package com.adcc.soundalarm.fx.alarm;

import com.adcc.soundalarm.entity.LogEntity;
import com.adcc.soundalarm.fx.main.MainView;
import com.adcc.soundalarm.sound.SoundAlarm;
import com.google.common.base.Strings;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;


/**
 * Created by ZHANG on 2017/3/31.
 */
public class AlarmDialogController {

    @FXML
    private Button btnConfirm;

    @FXML
    private TableView tableAlarm;

    @FXML
    private TableColumn columnLog;

    @FXML
    private TableColumn columnTime;

    @FXML
    private TableColumn columnImg;

    private ObservableList<LogEntity> strList = FXCollections.observableArrayList();

    private SoundAlarm soundAlarm = SoundAlarm.getInstance();

    // 当前舞台
    private Stage stage;

    public void buildEnvironment(Stage stage) {
        this.stage = stage;
    }

    @FXML
    protected void handleConfirmAction(ActionEvent actionEvent) {
        if (this.stage != null) {
            soundAlarm.setMuteFlag(true);
            this.stage.close();
        }
    }

    public void appendMessageToTextArea(LogEntity logEntity) {
        String url = Strings.nullToEmpty("");
        try {
            columnImg.setCellValueFactory(new PropertyValueFactory<>("img"));
            columnLog.setCellValueFactory(new PropertyValueFactory<>("log"));
            columnTime.setCellValueFactory(new PropertyValueFactory<>("createTime"));
            if (this.tableAlarm.getItems().size() >= 50 ) {
                this.tableAlarm.getItems().remove(0);
            }
            if ("WARN".equals(logEntity.getLevel())) {
                url = this.getClass().getResource("icon1.png").toString();
            } else if ("ALARM".equals(logEntity.getLevel())) {
                url = this.getClass().getResource("icon2.png").toString();
            } else {
                url = this.getClass().getResource("icon3.png").toString();
            }
            final ImageView imageview = new ImageView();
            imageview.setImage(new Image(url));
            logEntity.setImg(imageview);
            strList.add(logEntity);
            this.tableAlarm.setItems(strList);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 提示框隐藏
     */
    public void hide() {
        if (this.stage != null) {
            this.stage.close();
        }
    }
}
